<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/2
 * Time: 17:59
 */

namespace backend\controllers;


use backend\behaviors\AuthBehavior;
use yii\db\ActiveQuery;
use yii\web\Controller;
use Yii ;
use yii\web\Response;

class BackendBase extends Controller
{
    public $isJson = false ;
    public $isPost = false ;
    public $enableCsrfValidation = false ;
    private $_isRenderView = false ;

    public function behaviors()
    {
        return [
            AuthBehavior::className()   
        ];
    }

    public function init()
    {
        $this->isJson = ! (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/json') === false ) ;
        $this->isPost = $this->request()->getMethod() == 'POST' ;
        Yii::$app->response->format = Response::FORMAT_JSON ;
    }

    public function afterAction($action, $result)
    {
        $res  =  parent::afterAction($action, $result);
        if($this->_isRenderView){
            return $res ;
        }
        if($res === true){
            return ['code' => 0] ;
        }

        return $res ;
    }

    public function renderView($view , $params = []){
        $this->_isRenderView = true ;
        Yii::$app->response->format = Response::FORMAT_HTML ;
        return $this->render($view , $params) ;
    }

    public function request(){
        return \Yii::$app->request ;
    }

//    public function json(){
//        Yii::$app->response->format = Response::FORMAT_JSON ;
//    }

    public function page(ActiveQuery $query){
        $page = intval($this->request()->get('p',1)) ;
        $pagesize = intval($this->request()->get('pagesize',10)) ;
        $offset = $pagesize * ($page -1 ) ;
        $ret = [] ;
        $ret['code'] = 0 ;
        $ret['total'] = $query->count();
        $ret['current'] = $page ;
        $ret['rows']=$query->offset($offset)->limit($pagesize)->all() ;
        return $ret ;
    }
}